import {createRouter, createWebHistory} from 'vue-router'
import {useUserInfoStore} from '@/stores/userInfo'
import {getToken, removeToken} from '@/utils/token-utils'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: 'my',
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/pages/login/index.vue')
        },
        //首页
        {
            path: '/home',
            name: 'Home',
            component: () => import('@/pages/home/index.vue'),
        },
        //行情
        {
            path: '/market',
            name: 'Market',
            component: () => import('@/pages/market/index.vue')
        },
        //交易
        {
            path: '/trade',
            name: 'Trade',
            component: () => import('@/pages/trade/index.vue')
        },
        //圈子
        {
            path: '/circle',
            name: 'Circle',
            component: () => import('@/pages/circle/index.vue')
        },
        //我的
        {
            path: '/my',
            name: 'My',
            component: () => import('@/pages/my/index.vue')
        },
        //产品库
        {
            path: '/productLibrary',
            name: 'ProductLibrary',
            component: () => import('@/pages/home/productLibrary/index.vue')
        },
        //茶品牌
        {
            path: '/teaBrand',
            name: 'TeaBrand',
            component: () => import('@/pages/home/teaBrand/index.vue')
        },
        //全部圈子
        {
            path: '/findGroup',
            name: 'FindGroup',
            component: () => import('@/pages/circle/findGroup.vue')
        },
        //圈子详情
        {
            path: '/groupDetail/:groupId',
            name: 'GroupDetail',
            component: () => import('@/pages/circle/groupDetail.vue')
        },
        //动态详情
        {
            path: '/dynamicDetail/:dynamicId',
            name: 'DynamicDetail',
            component: () => import('@/pages/circle/dynamicDetail.vue')
        },
    ],
})
// 全局的前置守卫
router.beforeEach(async (to, form, next) => {
    const userInfoStore = useUserInfoStore()
    const token = getToken()
    //是否存在用户信息
    const isExistUserInfo = !!!userInfoStore.uid
    if (token) {
        //已经登录过，在进入登录页面，直接跳转到主页
        if (to.path == '/login') {
            next({path: "/"})
        } else {
            try {
                await userInfoStore.getInfo()
                next()
            } catch (error) {
                //自带的token有问题，我删除
                removeToken()
            }
        }
    } else {
        //没有token,这是没有登录，直接放行
        next()
    }
})


//全局的后置守卫

export default router
